<template>
  <AIEmbedChat
    :visible.sync="dialogVisible"
    title="Topic AI 数据分析"
    api-url="/cms/api/ai_chat/"
    handler-name="topic_analysis"
    :context-data="getContextData()"
    :suggested-questions="suggestedQuestions"
    placeholder="请输入您的分析需求，或点击上方的预设问题卡片..."
    :auto-parse-json="true"
    :left-span="12"
    :right-span="12"
    @dialog-opened="handleDialogOpened"
    @json-parsed="handleJsonParsed"
    @update:visible="$emit('update:visible', $event)"
  >
    <!-- 右侧：结构化数据展示和编辑 -->
    <template #right-panel>
      <div class="analysis-data-panel">
        <div class="panel-header">
          <h3>分析结果</h3>
          <el-button
            type="success"
            size="small"
            icon="el-icon-check"
            :loading="saving"
            @click="saveAnalysis"
          >
            保存分析结果
          </el-button>
        </div>

        <el-tabs v-model="activeTab" type="card">
          <!-- 核心关键词 -->
          <el-tab-pane :label="`核心关键词 (${analysisData.core_keywords.length})`" name="core">
            <el-table :data="analysisData.core_keywords" border size="small" max-height="500">
              <el-table-column label="关键词" width="360">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.keyword" size="small" placeholder="请输入关键词" />
                </template>
              </el-table-column>
              <el-table-column label="搜索量" width="100">
                <template slot-scope="scope">
                  <el-input v-model.number="scope.row.volume" size="small" type="number" placeholder="搜索量" />
                </template>
              </el-table-column>
              <el-table-column label="难度" width="80">
                <template slot-scope="scope">
                  <el-input v-model.number="scope.row.difficulty" size="small" type="number" placeholder="0-100" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" fixed="right">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    icon="el-icon-delete"
                    style="color: #F56C6C;"
                    @click="deleteKeyword('core_keywords', scope.$index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin-top: 10px;">
              <el-input
                v-model="batchInputCore"
                type="textarea"
                :rows="3"
                placeholder="批量添加关键词，每行一个。格式：关键词,搜索量,难度（搜索量和难度可选）"
                style="margin-bottom: 5px;"
              />
              <el-button type="primary" size="small" @click="handleBatchAdd('core_keywords')">批量添加</el-button>
              <el-button size="small" @click="showAddKeywordDialog('core_keywords')">单个添加</el-button>
            </div>
          </el-tab-pane>

          <!-- LSI关键词 -->
          <el-tab-pane :label="`LSI 关键词 (${analysisData.lsi_keywords.length})`" name="lsi">
            <el-table :data="analysisData.lsi_keywords" border size="small" max-height="500">
              <el-table-column label="关键词" width="400">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.keyword" size="small" placeholder="请输入LSI关键词" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" fixed="right">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    icon="el-icon-delete"
                    style="color: #F56C6C;"
                    @click="deleteKeyword('lsi_keywords', scope.$index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin-top: 10px;">
              <el-input
                v-model="batchInputLSI"
                type="textarea"
                :rows="3"
                placeholder="批量添加LSI关键词，每行一个"
                style="margin-bottom: 5px;"
              />
              <el-button type="primary" size="small" @click="handleBatchAdd('lsi_keywords')">批量添加</el-button>
              <el-button size="small" @click="showAddKeywordDialog('lsi_keywords')">单个添加</el-button>
            </div>
          </el-tab-pane>

          <!-- 相关关键词 -->
          <el-tab-pane :label="`相关关键词 (${analysisData.related_keywords.length})`" name="related">
            <el-table :data="analysisData.related_keywords" border size="small" max-height="500">
              <el-table-column label="关键词" width="400">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.keyword" size="small" placeholder="请输入相关关键词" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" fixed="right">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    icon="el-icon-delete"
                    style="color: #F56C6C;"
                    @click="deleteKeyword('related_keywords', scope.$index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin-top: 10px;">
              <el-input
                v-model="batchInputRelated"
                type="textarea"
                :rows="3"
                placeholder="批量添加相关关键词，每行一个"
                style="margin-bottom: 5px;"
              />
              <el-button type="primary" size="small" @click="handleBatchAdd('related_keywords')">批量添加</el-button>
              <el-button size="small" @click="showAddKeywordDialog('related_keywords')">单个添加</el-button>
            </div>
          </el-tab-pane>

          <!-- 动机判断 -->
          <el-tab-pane label="动机判断" name="intent">
            <el-form label-width="120px" size="small">
              <el-form-item label="搜索动机">
                <el-input v-model="analysisData.search_intent" type="textarea" :rows="5" />
              </el-form-item>
              <el-form-item label="内容需求类型">
                <el-input v-model="analysisData.content_type" type="textarea" :rows="5" />
              </el-form-item>
              <el-form-item label="核心价值">
                <el-input v-model="analysisData.core_value" type="textarea" :rows="5" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
    </template>

    <!-- 自定义footer -->
    <template #footer="{ close }">
      <el-button @click="close">关闭</el-button>
      <el-button type="success" :loading="saving" @click="saveAnalysis">保存分析结果</el-button>
    </template>
  </AIEmbedChat>
</template>

<script>
import AIEmbedChat from '@/components/AIEmbedChat'
import { getHandlerPrompts } from '@/api/ai_chat'
import { fetchTopicAnalysis, saveTopicAnalysis } from '@/api/topicanalysis'

export default {
  name: 'TopicAnalysisV2',
  components: {
    AIEmbedChat
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    topicData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      dialogVisible: false,
      activeTab: 'core',
      suggestedQuestions: [],
      analysisData: {
        core_keywords: [],
        lsi_keywords: [],
        related_keywords: [],
        search_intent: '',
        content_type: '',
        core_value: ''
      },
      batchInputCore: '',
      batchInputLSI: '',
      batchInputRelated: '',
      saving: false
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val

      if (!val) {
        // 对话框关闭时清空数据
        this.resetAnalysisData()
      }
      // 注意：不在这里验证数据，而是在 handleDialogOpened 中验证
      // 这样避免 drawer 还没打开就被关闭
    }
  },
  methods: {
    // 重置分析数据
    resetAnalysisData() {
      this.analysisData = {
        core_keywords: [],
        lsi_keywords: [],
        related_keywords: [],
        search_intent: '',
        content_type: '',
        core_value: ''
      }
      this.batchInputCore = ''
      this.batchInputLSI = ''
      this.batchInputRelated = ''
      this.activeTab = 'core'
    },

    // 获取上下文数据
    getContextData() {
      const topicId = this.topicData?.id || this.topicData?.topic_id

      return {
        topic_id: topicId
      }
    },

    // 验证 topicData
    validateTopicData() {
      const topicId = this.topicData?.id || this.topicData?.topic_id

      if (!topicId) {
        this.$message.error('缺少 Topic ID，无法进行分析。请确保已保存 Topic。')
        this.dialogVisible = false
        return false
      }
      return true
    },

    // 对话框打开时加载预设问题和已保存的分析数据
    async handleDialogOpened() {
      // 先验证数据
      if (!this.validateTopicData()) {
        return
      }

      try {
        // 并行加载预设问题和已保存的分析数据
        const [promptsRes, analysisRes] = await Promise.all([
          getHandlerPrompts('topic_analysis'),
          fetchTopicAnalysis(this.topicData.id)
        ])

        // 加载预设问题
        if (promptsRes.success && promptsRes.data.prompts) {
          this.suggestedQuestions = promptsRes.data.prompts
        }

        // 加载已保存的分析数据
        if (analysisRes.success && analysisRes.data) {
          // 数据直接在 data 下，不是 data[0].parsed_data
          this.loadSavedAnalysisData(analysisRes.data)
        }
      } catch (error) {
        console.error('加载数据失败:', error)
      }
    },

    // 加载已保存的分析数据
    loadSavedAnalysisData(parsedData) {
      // 加载核心关键词
      if (parsedData.core_keywords && Array.isArray(parsedData.core_keywords)) {
        this.analysisData.core_keywords = parsedData.core_keywords
      }

      // 加载 LSI 关键词
      if (parsedData.lsi_keywords && Array.isArray(parsedData.lsi_keywords)) {
        this.analysisData.lsi_keywords = parsedData.lsi_keywords
      }

      // 加载相关关键词
      if (parsedData.related_keywords && Array.isArray(parsedData.related_keywords)) {
        this.analysisData.related_keywords = parsedData.related_keywords
      }

      // 加载文本字段
      if (parsedData.search_intent) {
        this.analysisData.search_intent = parsedData.search_intent
      }
      if (parsedData.content_type) {
        this.analysisData.content_type = parsedData.content_type
      }
      if (parsedData.core_value) {
        this.analysisData.core_value = parsedData.core_value
      }

      this.$message.success('已加载保存的分析数据')
    },

    // 处理JSON解析结果
    handleJsonParsed(data) {
      // 合并核心关键词
      if (data.core_keywords && Array.isArray(data.core_keywords)) {
        data.core_keywords.forEach(item => {
          if (item.keyword) {
            this.analysisData.core_keywords.push({
              keyword: item.keyword,
              volume: item.volume || 0,
              difficulty: item.difficulty || 0
            })
          }
        })
      }

      // 合并LSI关键词
      if (data.lsi_keywords && Array.isArray(data.lsi_keywords)) {
        data.lsi_keywords.forEach(item => {
          if (item.keyword) {
            this.analysisData.lsi_keywords.push({
              keyword: item.keyword
            })
          }
        })
      }

      // 合并相关关键词
      if (data.related_keywords && Array.isArray(data.related_keywords)) {
        data.related_keywords.forEach(item => {
          if (item.keyword) {
            this.analysisData.related_keywords.push({
              keyword: item.keyword
            })
          }
        })
      }

      // 更新文本字段
      if (data.search_intent) {
        this.analysisData.search_intent = data.search_intent
      }
      if (data.content_type) {
        this.analysisData.content_type = data.content_type
      }
      if (data.core_value) {
        this.analysisData.core_value = data.core_value
      }

      this.$message.success('AI分析结果已自动填充到右侧面板')
    },

    // 删除关键词
    deleteKeyword(type, index) {
      this.analysisData[type].splice(index, 1)
    },

    // 显示添加关键词对话框
    showAddKeywordDialog(type) {
      if (type === 'core_keywords') {
        this.$prompt('请输入关键词信息（格式：关键词,搜索量,难度）', '添加核心关键词', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(({ value }) => {
          const parts = value.split(',').map(p => p.trim())
          this.analysisData.core_keywords.push({
            keyword: parts[0] || '',
            volume: parseInt(parts[1]) || 0,
            difficulty: parseInt(parts[2]) || 0
          })
        }).catch(() => {})
      } else {
        this.$prompt('请输入关键词', `添加${type === 'lsi_keywords' ? 'LSI' : '相关'}关键词`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(({ value }) => {
          if (value && value.trim()) {
            this.analysisData[type].push({
              keyword: value.trim()
            })
          }
        }).catch(() => {})
      }
    },

    // 批量添加
    handleBatchAdd(type) {
      let inputText = ''
      if (type === 'core_keywords') {
        inputText = this.batchInputCore
      } else if (type === 'lsi_keywords') {
        inputText = this.batchInputLSI
      } else if (type === 'related_keywords') {
        inputText = this.batchInputRelated
      }

      if (!inputText.trim()) {
        this.$message.warning('请输入关键词')
        return
      }

      const lines = inputText.split('\n').filter(line => line.trim())
      let addedCount = 0

      lines.forEach(line => {
        const trimmedLine = line.trim()
        if (!trimmedLine) return

        if (type === 'core_keywords') {
          const parts = trimmedLine.split(',').map(p => p.trim())
          const keyword = parts[0]
          const volume = parts[1] ? parseInt(parts[1]) || 0 : 0
          const difficulty = parts[2] ? parseInt(parts[2]) || 0 : 0

          if (keyword) {
            this.analysisData.core_keywords.push({ keyword, volume, difficulty })
            addedCount++
          }
        } else {
          this.analysisData[type].push({ keyword: trimmedLine })
          addedCount++
        }
      })

      // 清空输入框
      if (type === 'core_keywords') {
        this.batchInputCore = ''
      } else if (type === 'lsi_keywords') {
        this.batchInputLSI = ''
      } else if (type === 'related_keywords') {
        this.batchInputRelated = ''
      }

      this.$message.success(`成功添加 ${addedCount} 个关键词`)
    },

    // 保存分析结果
    async saveAnalysis() {
      this.saving = true
      try {
        const res = await saveTopicAnalysis({
          topic_id: this.topicData.id,
          parsed_data: this.analysisData
        })

        if (res.success) {
          this.$message.success('保存成功')
          this.$emit('saved', this.analysisData)
        } else {
          this.$message.error(res.msg || '保存失败')
        }
      } catch (error) {
        console.error('保存失败:', error)
        this.$message.error('保存失败: ' + error.message)
      } finally {
        this.saving = false
      }
    }
  }
}
</script>

<style scoped lang="scss">
.analysis-data-panel {
  height: 100%;
  display: flex;
  flex-direction: column;

  .panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e4e7ed;

    h3 {
      margin: 0;
      font-size: 16px;
      color: #303133;
    }
  }

  ::v-deep .el-tabs {
    flex: 1;
    display: flex;
    flex-direction: column;

    .el-tabs__content {
      flex: 1;
      overflow-y: auto;
    }
  }
}
</style>
